<?php
require_once 'html-extractor.php';
require_once 'file_php.php';
require_once 'Utils.php';
require_once 'Item.php';

$debug = false;

$imageUrls = array (
		"http://image.baidu.com/i?ct=201326592&cl=2&lm=-1&nc=1&ie=utf-8&tn=baiduimage&pv=&fm=rs1&word=%E5%8E%86%E5%8F%B2%E4%B8%8A%E7%9A%84%E4%BB%8A%E5%A4%A9",
		"http://image.baidu.com/i?tn=baiduimage&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1356955491562_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8E%86%E5%8F%B2%E4%B8%8A%E7%9A%84%E7%94%84%E5%AC%9B&f=3&oq=%E5%8E%86%E5%8F%B2%E4%B8%8A%E7%9A%84&rsp=4",
		"http://image.baidu.com/i?tn=baiduimage&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1356955578305_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8E%86%E5%8F%B2%E5%B0%8F%E6%8A%A5&f=3&oq=%E5%8E%86%E5%8F%B2&rsp=1" 
);

/**
 * return item's array
 *
 * @param unknown_type $content        	
 */
function getItemArray($content) {
	global $debug;
	return json_decode ( $content, true );
}

/**
 *
 * @param unknown_type $item        	
 * @return Item false when failure
 */
function getItem($item) {
	global $debug;
	global $todayUrl;
	// get title and link
	$title = "";
	$link = "";
	if (preg_match ( '/title="([\s\S]*)"/m', $item, $regs )) {
		$title = $regs [1];
		if ($debug) {
			echo "title:" . $title . '<br/>';
		}
	} else {
		if ($debug) {
			echo "no title:" . '<br/>';
		}
		return false;
	}
	
	if (preg_match ( '/href="([^=]*)"/m', $item, $regs )) {
		$link = $regs [1];
		if ($debug) {
			
			echo "link:" . $link . '<br/>';
		}
	} else {
		if ($debug) {
			
			echo "no link:" . '<br/>';
		}
		return false;
	}
	// get image
	$images = array ();
	$image = "";
	if (preg_match ( '/rel="([^=]*)"/m', $item, $regs )) {
		if ($regs [1] [0] == '/') {
			$image = $todayUrl . substr ( $regs [1], 1, strlen ( $regs [1] ) - 1 );
		} else {
			$image = $todayUrl . $regs [1];
		}
		if ($debug) {
			echo "image:" . $image . '<br/>';
		}
	} else {
		if ($debug) {
			echo "no image:" . '<br/>';
		}
		return false;
	}
	array_push ( $images, $image );
	return new Item ( $title, $images, $link, "", "" );
}
function stripTagsAndEmbraceWithCData($title) {
	return "<![CDATA[" . strip_tags ( $title ) . "]]>";
}
function saveAsFile($destFile, $url) {
	if (true) {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_POST, 0 );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		$file_content = curl_exec ( $ch );
		curl_close ( $ch );
		
		$downloaded_file = fopen ( $destFile, 'w' );
		fwrite ( $downloaded_file, $file_content );
		fclose ( $downloaded_file );
	} else {
		$context = stream_context_create ( array (
				'http' => array (
						'protocol_version' => '1.1',
						'method' => 'get',
						'header' => 'User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/522.11.1 (KHTML, like Gecko) Version/3.0.3 Safari/522.12.1' 
				) 
		) );
		
		$data = file_get_contents ( $url, false, $context );
		file_put_contents ( $destFile, $data );
	}
}
function getImgesEvent() {
	global $imageUrls;
	global $debug;
	$kFileDir = Utils::getDataPath ();
	$date_format = "n-j";
	// if true, good; if false, zip creation failed
	$zipFile = $kFileDir . 'imageevents.zip';
	$xmlFile = $kFileDir . 'imageevents.xml';
	
	// file updated
	if (! $debug && file_exists ( $zipFile ) && (Utils::getTime ( $date_format, filemtime ( $zipFile ) ) === Utils::getToday ( $date_format ))) {
		echo "file zipped" . '<br/>';
		return;
	}
	
	$files_to_zip = array ();
	$file = new file_php ( $xmlFile );
	$file->open ();
	$file->write ( "\xEF\xBB\xBF" );
	$file->writeutf8 ( Utils::getRssHeader () );
	
	$count = 0;
	$largeTnImageUrl = "largeTnImageUrl";
	$hoverURL = "hoverURL";
	$fromPageTitle = "fromPageTitle";
	$bdImgnewsDate = "bdImgnewsDate";
	// echo "getcwd ".getcwd() . "<br/>";
	// echo "SERVER_NAME ".$_SERVER['SERVER_NAME'].'<br/>';
	
	foreach ( $imageUrls as $imageUrl ) {
		$subject = HTMLExtractor::getUrlHtml ( $imageUrl );
		// match content segment
		if (preg_match ( '/"data":([\s\S]*\}\])/m', $subject, $regs )) {
			$result = $regs [1];
		} else {
			$result = "";
		}
		// echo $result . '<br/>';
		// match item by item with json
		$items = getItemArray ( $result );
		foreach ( $items as $value ) {
			// arrange them into rss
			$imageLink = $value [$hoverURL];
			if (! strlen ( $imageLink )) {
				$imageLink = $value [$largeTnImageUrl];
			}
			$imageFile = $kFileDir . $count;
			$title = stripTagsAndEmbraceWithCData ( $value [$fromPageTitle] );
			// $imageLink =urlencode($imageLink);
			$suffix = strrchr ( $imageLink, '.' );
			if (false != $suffix) {
				$imageFile .= $suffix;
				if ($debug) {
					echo "$imageFile " . $imageFile . '<br/>';
				}
			}
			// saveAsFile ( $imageFile, $imageLink );
			
			// $imageTransferUrl = $_SERVER['SERVER_NAME'].'/'.getcwd();
			$imageLink = urlencode ( $imageLink );
			$item = new Item ( $title, $imageLink, $imageLink, $value [$bdImgnewsDate], $value [$fromPageTitle] );
			
			$file->write ( $item->getRss () );
			$count ++;
		}
	}
	if ($debug) {
		echo "count" . $count . '<br/>';
	}
	$file->write ( Utils::getRssTail () );
	$file->close ();
	
	file_php::create_zip ( array (
			$xmlFile 
	), $zipFile, true );
}
function getImagesEventJson() {
	$kFileDir = Utils::getDataPath ();
	global $imageUrls;
	global $debug;
	
	$date_format = "n-j";
	// if true, good; if false, zip creation failed
	$zipFile = $kFileDir . 'imageevents.zip';
	$jsonFile = $kFileDir . 'imageevents.json';
	
	// file updated
	if (! $debug && file_exists ( $zipFile ) && (Utils::getTime ( $date_format, filemtime ( $zipFile ) ) === Utils::getToday ( $date_format ))) {
		echo "file zipped" . '<br/>';
		return;
	}
	
	$files_to_zip = array ();
	
	$count = 0;
	$largeTnImageUrl = "largeTnImageUrl";
	$hoverURL = "hoverURL";
	$fromPageTitle = "fromPageTitle";
	$bdImgnewsDate = "bdImgnewsDate";
	$jsonArray = array ();
	foreach ( $imageUrls as $imageUrl ) {
		$subject = HTMLExtractor::getUrlHtml ( $imageUrl );
		// match content segment
		if (preg_match ( '/"data":([\s\S]*\}\])/m', $subject, $regs )) {
			$result = $regs [1];
		} else {
			$result = "";
		}
		$items = getItemArray ( $result );
		foreach ( $items as $value ) {
			// arrange them into rss
			$imageLink = $value [$hoverURL];
			if (! strlen ( $imageLink )) {
				$imageLink = $value [$largeTnImageUrl];
			}
			$imageFile = $kFileDir . $count;
			$title = strip_tags ( $value [$fromPageTitle] );
			
			$suffix = strrchr ( $imageLink, '.' );
			if (false != $suffix) {
				$imageFile .= $suffix;
				if ($debug) {
					echo "$imageFile " . $imageFile . '<br/>';
				}
			}
			// get remote file and save
			file_php::writeJson ( $imageFile, file_php::getRemoteFile ( $imageLink ), false );
			
			if (strlen ( $title ) && strlen ( $imageLink )) {
				$item = new Item ( $title, $imageLink, $imageLink, $value [$bdImgnewsDate], $title );
				$jsonArray [] = $item;
				$count ++;
			}
		}
	}
	
	file_php::writeJson ( $jsonFile, json_encode ( $jsonArray ) );
	
	if ($debug) {
		echo "count" . $count . '<br/>';
	}
	
	file_php::create_zip ( array (
			$jsonFile 
	), $zipFile, true );
}
function getGoogleImageEvents() {
	$searches = array (
			"%E5%8E%86%E5%8F%B2%E4%B8%8A%E7%9A%84%E4%BB%8A%E5%A4%A9",
			"%E8%80%81%E7%85%A7%E7%89%87" 
	);
	$results = array ();
	// get more google search result
	foreach ( $searches as $q ) {
		$r = file_php::getGoogleImagesMaxJson ( $q );
		$results = array_merge ( $results, json_decode ( $r, true ) );
	}
	// echo "google result: " . $r . '<br/>';
	$kFileDir = Utils::getDataPath ();
	$zipFile = $kFileDir . 'imageevents.zip';
	$jsonFile = $kFileDir . 'imageevents.json';
	file_php::writeJson ( $jsonFile, json_encode ( $results ), true );
	
	file_php::create_zip ( array (
			$jsonFile 
	), $zipFile, true );
}
// run this script
set_time_limit ( 0 );
$kDefaultUrl = "http://www.idreems.com/example.php?php/imagesearch/data/searchindex.txt";
$kDefaultKeyword = "%E5%8E%86%E5%8F%B2%E4%B8%8A%E7%9A%84%E4%BB%8A%E5%A4%A9";
$kKeywordMinLength = 1;

$queryString = $_GET ["q"];
$seachKeyword = $_GET ["d"];

$logKeyword2File = true;
if (false != $seachKeyword) {
	header ( "location:" . $kDefaultUrl );
} else if (false != $queryString) {
	if(strlen($queryString)<=$kKeywordMinLength)
	{
		$queryString = $kDefaultKeyword;
	}
	// echo 'queryString: '.$queryString.'<br/>';
	$r = file_php::getGoogleImagesMaxJson ( $queryString );
	// return to client
	header ( 'Content-type: text/json' );
	$r = json_decode ( $r, true );
	$size = count ( $r );
	$r = array (
			'data' => $r 
	);
	echo json_encode ( $r );
	
	if ($size > 0 && $logKeyword2File) {
		// write to file
		$time = Utils::getTime ( DATE_ATOM, time () );
		file_php::appendString ( "data\\search.txt", $queryString . "\t$size" . "\t" . $time );
	}
} else {
	print ("<html><body>Bad request.</body></html>") ;
}
?>


